package com.cc.blog.common.exception;

import com.cc.blog.common.enums.CodeEnum;
import com.cc.blog.common.utils.MessageUtils;
import com.cc.blog.common.utils.Result;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义异常
 * @author cc
 */
@Slf4j
public class BusinessException extends RuntimeException {

    private static final long serialVersionUID = 3152549963899218489L;
    @Setter
    @Getter
    private String errorMsg;
    @Setter
    @Getter
    private String errorCode;
    @Setter
    @Getter
    private Object data;

    public BusinessException() {
        super(CodeEnum.FAIL.getMsg());
        this.errorCode = CodeEnum.FAIL.getMsg();
        this.errorMsg = CodeEnum.FAIL.getCode();
    }

    public BusinessException(String errorCode, String errorDesc) {
        super(errorDesc);
        this.errorCode = errorCode;
        this.errorMsg = errorDesc;
    }

    public BusinessException(CodeEnum resultCode) {
        super(resultCode.getMsg());
        this.errorCode = resultCode.getCode();
        this.errorMsg = resultCode.getMsg();
        log.error("业务异常: {}", this);
    }


    public BusinessException(Result<?> result) {
        super(result == null ? CodeEnum.FAIL.getMsg() : result.getMsg());
        if (result == null) {
            this.errorCode = CodeEnum.FAIL.getCode();
            this.errorMsg = CodeEnum.FAIL.getMsg();
        } else {
            this.errorCode = result.getCode();
            this.errorMsg = result.getMsg();
            this.data = result.getData();
        }
        log.error("业务异常: {}", this);
    }

    public BusinessException(String message) {
        super(message);
    }

    public BusinessException(Throwable cause) {
        super(cause);
        log.error("业务异常: {}", this);
    }

    public BusinessException(String message, Throwable cause) {
        super(message, cause);
        log.error("业务异常: {}", this);
    }

    public BusinessException(String code, String[] params) {
        this.errorCode = code;
        this.errorMsg = MessageUtils.getMessage(code, params);
    }
}